<template>
  <a-spin :spinning="loading">
    <div class="question-select">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <div class="filter-row">
          <div class="filter-item">
            <label class="filter-label">题目类型:</label>
            <a-select
              v-model:value="filterParams.isPublic"
              placeholder="请选择题目类型"
              allow-clear
              @change="handleFilterChange"
              class="filter-input"
            >
              <a-select-option :value="0">计分题</a-select-option>
              <a-select-option :value="1">基础信息题</a-select-option>
              <a-select-option :value="2">调查问卷题</a-select-option>
              <!-- <a-select-option :value="3">关联题</a-select-option> -->
               <a-select-option :value="4">赋分题</a-select-option>
            </a-select>
          </div>
          <div class="filter-item">
            <label class="filter-label">题目内容:</label>
            <a-input
              v-model:value="filterParams.content"
              placeholder="请输入题目内容"
              allow-clear
              @keyup.enter="handleFilterChange"
              class="filter-input"
            />
          </div>
          <div class="filter-item button-item">
            <a-button type="primary" @click="handleFilterChange" preIcon="ant-design:search-outlined">查询</a-button>
            <!-- <a-button style="margin-left: 8px" @click="handleReset" preIcon="ant-design:reload-outlined">重置</a-button> -->
          </div>
        </div>
      </div>

      <!-- 编辑模式提示信息 -->
      <div v-if="isEditMode" class="edit-mode-tip" style="margin-bottom: 16px;">
        <a-alert
          message="编辑模式：请选择一条数据来替换当前题目"
          type="info"
          show-icon
        />
      </div>

      <a-table
        :dataSource="questionList"
        :columns="columns"
        :rowKey="rowKey"
        :rowSelection="rowSelection"
        :pagination="pagination"
        @change="handleTableChange"
      />
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { ContentTypeEnum } from '/@/enums/httpEnum';
  import { message } from 'ant-design-vue';
  import { publicList, publicEdit, publicSync } from '../ExamQuestions.api';

  export default defineComponent({
    name: 'ExamQuestionsForm',
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      par_id: Number, // 题库ID（examQuestionBankId）
      formData: { type: Object, default: () => ({}) },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const loading = ref(false);
      const questionList = ref<Record<string, any>[]>([]);
      const selectedRowKeys = ref<string[] | number[]>([]);
      const pagination = reactive({ current: 1, pageSize: 10, total: 0, showSizeChanger: true });
      
      // 筛选参数
      const filterParams = reactive({
        isPublic: undefined,
        content: '',
      });

      // 判断是否为编辑模式
      const isEditMode = computed(() => {
        return props.formData && props.formData.id;
      });

      // 当前编辑的数据ID
      const currentEditId = computed(() => {
        return props.formData?.id;
      });

      const columns = [
        { title: '题目内容', dataIndex: 'content' },
        { title: '题目类型', dataIndex: 'typeLabel' },
      ];

      const disabled = computed(() => {
        if (props.formBpm === true) {
          if (props.formData && (props as any).formData.disabled === false) {
            return false;
          } else {
            return true;
          }
        }
        return props.formDisabled;
      });

      const rowKey = (record: any) => record.id;

      const rowSelection = reactive({
        type: isEditMode.value ? 'radio' : 'checkbox', // 编辑模式为单选，新增模式为多选
        selectedRowKeys: selectedRowKeys.value,
        onChange: (keys: any[]) => {
          selectedRowKeys.value = keys;
          (rowSelection as any).selectedRowKeys = keys;
        },
        getCheckboxProps: () => ({ disabled: disabled.value }),
      });

      async function fetchList() {
        loading.value = true;
        try {
          const params: any = {
            pageNo: pagination.current,
            pageSize: pagination.pageSize,
            ...filterParams, // 添加筛选参数
          };
          const res: any = await publicList(params);
          const records = (res && (res.records || res)) || [];
          pagination.total = (res && (res.total || 0)) || records.length || 0;
          const TYPE_MAP: Record<number, string> = { 0: '计分题', 1: '基础信息题', 2: '调查问卷题', 3: '关联题' };
          questionList.value = records.map((r: any) => ({
            ...r,
            typeLabel: TYPE_MAP[Number(r.isPublic)] || '',
          }));

          // 如果是编辑模式，默认选中当前编辑的数据
          if (isEditMode.value && currentEditId.value) {
            const currentRecord = questionList.value.find(item => item.id === currentEditId.value);
            if (currentRecord) {
              selectedRowKeys.value = [currentEditId.value];
              (rowSelection as any).selectedRowKeys = [currentEditId.value];
            }
          }
        } finally {
          loading.value = false;
        }
      }

      function handleTableChange(p: any) {
        pagination.current = p.current;
        pagination.pageSize = p.pageSize;
        fetchList();
      }

      /**
       * 筛选变化事件
       */
      function handleFilterChange() {
        pagination.current = 1; // 重置到第一页
        fetchList();
      }

      /**
       * 重置筛选
       */
      function handleReset() {
        filterParams.isPublic = undefined;
        filterParams.content = '';
        pagination.current = 1; // 重置到第一页
        fetchList();
      }

      async function submitForm() {
        if (!props.par_id) {
          message.warning('缺少题库ID');
          return;
        }
        if (selectedRowKeys.value.length === 0) {
          message.warning('请先勾选题目');
          return;
        }

        // 编辑模式下只允许选择一条数据
        if (isEditMode.value && selectedRowKeys.value.length > 1) {
          message.warning('编辑模式下只能选择一条数据进行替换');
          return;
        }

        loading.value = true;
        try {
          if (isEditMode.value) {
            // 编辑模式：调用编辑接口
            const selectedId = selectedRowKeys.value[0];
            const selectedRecord = questionList.value.find(item => item.id === selectedId);
            
            if (!selectedRecord) {
              message.error('未找到选中的数据');
              return;
            }

            // 构建编辑参数
            const editParams = {
              id: props.formData.id, // 当前编辑的题目ID
              bankId: props.par_id,
              content: selectedRecord.content,
              isMultipleChoice: selectedRecord.isMultipleChoice,
              isPublic: selectedRecord.isPublic,
              valueOfScore: selectedRecord.valueOfScore,
              correctAnswer: selectedRecord.correctAnswer,
              other: selectedRecord.other || '',
              other2: selectedRecord.other2 || '',
              examOptionsList: selectedRecord.examOptionsList || []
            };

            await publicEdit(editParams);
            message.success('替换成功');
          } else {
            // 新增模式：调用同步接口
            await publicSync({
              ids: selectedRowKeys.value.join(','),
              examQuestionBankId: props.par_id,
            });
            message.success('同步成功');
          }
          
          emit('success');
        } finally {
          loading.value = false;
        }
      }

      onMounted(() => {
        fetchList();
      });

      return {
        loading,
        questionList,
        columns,
        rowSelection,
        rowKey,
        pagination,
        selectedRowKeys,
        handleTableChange,
        handleFilterChange,
        handleReset,
        submitForm,
        disabled,
        filterParams,
        isEditMode,
        currentEditId, // 添加 currentEditId 到返回值
      };
    },
  });
</script>

<style lang="less" scoped>
.question-select {
  padding: 12px 4px;
}

.filter-container {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  margin-bottom: 16px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  min-width: 70px;
  text-align: right;
}

.filter-input {
  width: 200px;
}

.button-item {
  margin-left: auto;
}

:deep(.ant-select) {
  width: 200px;
}

:deep(.ant-input) {
  width: 200px;
}
</style>
